package com.gmrz.uap.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Wang Haifeng
 */
public class SystemFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(SystemFilter.class);


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求数据
        String method = request.getMethod();
        log.info("method:{}", method);
        String url = request.getRequestURL().toString();
        log.info("url:{}", url);

        if ("POST".equalsIgnoreCase(method)) {
            // 获取 POST 请求的请求体数据
            String requestBody = request.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);
            log.info("body:{}", requestBody);
        }

        // 执行下一个过滤器或Servlet
        filterChain.doFilter(request, response);

        // 获取响应数据
        int status = response.getStatus();
        log.info("status:{}", status);
    }
}
